import 'dart:io';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;
import 'package:video_thumbnail/video_thumbnail.dart';
import '../../../function/model/post_model.dart';
import '../../../function/state/post_state.dart';
import '../../../function/state/user_state.dart';
import '../../../function/widgets/custom_snackbar.dart';
import '../../../function/widgets/login_dialog_widget.dart';

/// 发布帖子页面控制器
class PostPublishController extends GetxController {
  // 文本控制器
  final TextEditingController titleController = TextEditingController();
  final TextEditingController contentController = TextEditingController();

  // 响应式变量
  final Rx<AssetEntity?> selectedAsset = Rx<AssetEntity?>(null);
  final Rx<PostCategory> selectedCategory =
      PostCategory.plantGrowthChallenge.obs;
  final RxList<String> selectedLabels = <String>['Vibrant'].obs;
  final RxBool isPublishing = false.obs;

  // 可用的标签选项
  final List<String> availableLabels = [
    'Vibrant',
    'Green',
    'Healthy',
    'Growing',
    'Beautiful',
    'Fresh',
    'Natural',
    'Organic',
    'Thriving',
    'Lush',
  ];

  @override
  void onClose() {
    titleController.dispose();
    contentController.dispose();
    super.onClose();
  }

  /// 选择资源（图片或视频）
  Future<void> selectResource() async {
    try {
      final List<AssetEntity>? assets = await AssetPicker.pickAssets(
        Get.context!,
        pickerConfig: const AssetPickerConfig(
          maxAssets: 1,
          requestType: RequestType.common,
          specialPickerType: SpecialPickerType.noPreview,
        ),
      );

      if (assets != null && assets.isNotEmpty) {
        selectedAsset.value = assets.first;
      }
    } catch (e) {
      CustomSnackBar.error('Failed to select resource: $e');
    }
  }

  /// 处理选择的资源
  Future<String?> _processSelectedAsset() async {
    final asset = selectedAsset.value;
    if (asset == null) return null;

    try {
      // 获取应用文档目录
      final Directory appDocDir = await getApplicationDocumentsDirectory();
      final String mediaDir = path.join(appDocDir.path, 'media');

      // 确保媒体目录存在
      await Directory(mediaDir).create(recursive: true);

      // 生成唯一文件名
      final String timestamp = DateTime.now().millisecondsSinceEpoch.toString();
      String extension = 'jpg'; // 默认扩展名

      // 根据资源类型确定正确的扩展名
      if (asset.type == AssetType.video) {
        extension = 'mp4'; // 视频文件使用mp4扩展名
      } else if (asset.mimeType != null) {
        extension = asset.mimeType!.split('/').last;
      }

      final String fileName = '$timestamp.$extension';
      final String filePath = path.join(mediaDir, fileName);

      // 复制文件到本地目录
      final File? file = await asset.file;
      if (file != null) {
        await file.copy(filePath);

        // 对于视频和图片，都返回文件路径
        // 缩略图生成在UI层面处理，这里只负责文件复制
        return filePath;
      }
    } catch (e) {
      CustomSnackBar.error('Failed to process resource: $e');
    }

    return null;
  }

  /// 生成视频封面图
  Future<String?> _generateVideoCover(String videoPath) async {
    try {
      final Directory appDocDir = await getApplicationDocumentsDirectory();
      final String thumbnailDir = path.join(appDocDir.path, 'thumbnails');

      // 确保目录存在
      await Directory(thumbnailDir).create(recursive: true);

      final String timestamp = DateTime.now().millisecondsSinceEpoch.toString();
      final String thumbnailFileName = 'cover_$timestamp.jpg';
      final String thumbnailPath = path.join(thumbnailDir, thumbnailFileName);

      final String? thumbnail = await VideoThumbnail.thumbnailFile(
        video: videoPath,
        thumbnailPath: thumbnailPath,
        imageFormat: ImageFormat.JPEG,
        quality: 75,
        maxHeight: 200,
      );

      if (thumbnail != null) {
        return thumbnail;
      } else {
        return null;
      }
    } catch (e) {
      return null;
    }
  }

  /// 选择分类
  void selectCategory(PostCategory category) {
    selectedCategory.value = category;
  }

  /// 添加标签
  void addLabel(String label) {
    if (selectedLabels.length < 5 && !selectedLabels.contains(label)) {
      selectedLabels.add(label);
    }
  }

  /// 移除标签
  void removeLabel(String label) {
    selectedLabels.remove(label);
  }

  /// 发布帖子
  Future<void> publishPost() async {
    // 检查用户是否已登录
    final UserState userState = Get.find<UserState>();
    if (!userState.isLoggedIn) {
      LoginDialogUtils.showLoginDialog();
      return;
    }

    // 验证输入
    if (titleController.text.trim().isEmpty) {
      CustomSnackBar.warning('Please enter a title');
      return;
    }

    if (contentController.text.trim().isEmpty) {
      CustomSnackBar.warning('Please enter content');
      return;
    }

    if (selectedAsset.value == null) {
      CustomSnackBar.warning('Please select an image or video');
      return;
    }

    isPublishing.value = true;

    try {
      // 处理选择的资源
      final String? resourcePath = await _processSelectedAsset();
      if (resourcePath == null) {
        throw Exception('Failed to process resource');
      }

      // 如果是视频，生成封面图
      String? coverImagePath;
      if (selectedAsset.value!.type == AssetType.video) {
        coverImagePath = await _generateVideoCover(resourcePath);
      }

      // 创建帖子模型
      final PostModel newPost = PostModel(
        id: DateTime.now().millisecondsSinceEpoch.toString(),
        userId: userState.currentUser!.id,
        category: selectedCategory.value,
        title: titleController.text.trim(),
        content: contentController.text.trim(),
        tags: selectedLabels.toList(),
        resourceType:
            selectedAsset.value!.type == AssetType.video
                ? ResourceType.video
                : ResourceType.image,
        resourcePath: resourcePath,
        coverImagePath: coverImagePath,
        publishTime: DateTime.now(),
      );

      // 添加到帖子状态
      final PostState postState = Get.find<PostState>();
      postState.addPost(newPost);

      // 显示成功消息
      CustomSnackBar.success('Post published successfully!');

      // 返回上一页
      Get.back();
    } catch (e) {
      CustomSnackBar.error('Failed to publish post: $e');
    } finally {
      isPublishing.value = false;
    }
  }

  /// 获取资源类型
  ResourceType? get resourceType {
    final asset = selectedAsset.value;
    if (asset == null) return null;
    return asset.type == AssetType.video
        ? ResourceType.video
        : ResourceType.image;
  }

  /// 获取资源预览路径
  Future<String?> get resourcePreviewPath async {
    final asset = selectedAsset.value;
    if (asset == null) return null;
    final file = await asset.file;
    return file?.path;
  }
}
